import {
  login,
  logout,
  getInfo,
  getCurrentUserNeedRemindScheduleInThatMinute
} from '@/api/user'

// eslint-disable-next-line no-unused-vars
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import CryptoJS from '@/utils/crypto'

const state = {
  token: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  }
}

const actions = {
  // 登录$$.encr
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    const formData = {
      act: username.trim(),
      pwd: CryptoJS.encrypt(password)
    }
    return new Promise((resolve, reject) => {
      login(formData)
        .then(response => {
          localStorage.setItem('user', JSON.stringify(response.USERINFO))
          localStorage.setItem('power', JSON.stringify(response.POWER))
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 拿到用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 退出
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          setToken('')
          removeToken()
          localStorage.removeItem('user')
          localStorage.removeItem('power')
          resetRouter()

          // 把缓存的tags清空重置
          dispatch('tagsView/delAllViews', null, { root: true })
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
